package org.csu.gp_store.util;

import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtil {

    /**
     * token秘钥，请勿泄露，请勿随便修改
     */
    public static final String SECRET = "GP_Store";
    /**
     * token 过期时间: 7天
     */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 7;


    /**
     * JWT生成Token.<br/>
     * <p>
     * JWT构成: header, payload, signature
     *
     * @param username 登录成功后用户username, 参数username不可传空
     */
    public static String createToken(String username) {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("algorithm", "HS256");
        map.put("type", "JWT");

        // build token
        String token = JWT.create().withHeader(map) // header
                //.withClaim("iss", "Service") // payload
                //.withClaim("aud", "APP")
                .withClaim("userId", username)
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature签名

        return token;
    }


    /**
     * 解密Token,失败返回null
     *
     * @param token token
     * @return Map<String, Claim>
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            // token 校验失败, 抛出Token验证非法异常
            return null;
        }
        return jwt.getClaims();
    }


    /**
     * 根据Token获取userId
     *
     * @param token token
     * @return userId 校验失败返回null
     */
    public static String getUserIdByToken(String token) {
        Map<String, Claim> claims = TokenUtil.verifyToken(token);
        if (claims == null) {
            // token 校验失败
            return null;
        }
        Claim userIdClaim = claims.get("userId");
        if (null == userIdClaim || StringUtils.isEmpty(userIdClaim.asString())) {
            // token 校验失败
            return null;
        }
        return (userIdClaim.asString());
    }

    public static void main(String[] args) {
        System.out.println(createToken("1357849499336704"));
    }
}
